<template>
  <div class="login">
    <div class="login-form">
      <div class="login-top">
        <span class="login-top-title">登录</span>
        <a class="login-type" href="javascript:void(0);" @click="loginTypeChange">
          {{ login_type === 1 ? "使用账号登录" : "微信扫码登录" }}
        </a>
      </div>
      <div class="form-title">
        <h2>{{ defaultSettings.title }}</h2>
      </div>

      <div v-if="login_type === 1">
        <div class="qrcode-box">
          <qrcode-vue :value="qrcodeUrl" :size="300" level="H" />
          <div v-if="isExpire" class="meng-box">
            <div class="meng-tips">二维码已过期</div>
            <el-button type="success" size="default" @click="onRefreshQrcode">刷新</el-button>
          </div>
        </div>
        <div class="login-tips">微信扫一扫，快捷登录</div>
      </div>

      <div v-else-if="login_type === 2" class="login-form-content">
        <el-form
          ref="ruleFormRef"
          :model="login"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item prop="username">
            <el-input
              v-model="login.username"
              prefix-icon="User"
              size="large"
              placeholder="账号"
              style="width: 320px"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="login.password"
              prefix-icon="Lock"
              size="large"
              type="password"
              placeholder="密码"
              style="width: 320px"
            />
          </el-form-item>
          <div class="login-option">
            <el-checkbox v-model="is_save" size="large">记住密码</el-checkbox>
            <a class="reset-pass" href="javascript:void(0);">忘记密码？</a>
          </div>
          <el-form-item>
            <el-button
              size="large"
              type="primary"
              style="width: 320px"
              :loading="loading"
              @click="onLogin"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import QrcodeVue from "qrcode.vue";
import AuthAPI from "@/api/auth";
import defaultSettings from "@/settings";
import { LocationQuery, useRoute } from "vue-router";
import router from "@/router";
import { setToken, setRefreshToken } from "@/utils/auth";
import { useUserStore } from "@/store";
import type { FormInstance, FormRules } from "element-plus";
import webSocketManager from "@/utils/websocket";

let timeId;
const loading = ref(false);
const is_save = ref(false);
const login_type = ref(1); // 1扫码登录 2账号密码登录
const userStore = useUserStore();
const qrcodeUrl = ref("");
const isExpire = ref(false);
const route = useRoute();
const ruleFormRef = ref<FormInstance>();
const login = ref({
  username: "",
  password: "",
});

interface RuleForm {
  username: string;
  password: string;
}

const rules = reactive<FormRules<RuleForm>>({
  username: [{ required: true, message: "请输入账号", trigger: "change" }],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "change",
    },
  ],
});

function loginTypeChange() {
  if (login_type.value === 1) {
    clearInterval(timeId);
    isExpire.value = true;
    timeId = null;
    login_type.value = 2;
  } else if (login_type.value === 2) {
    isExpire.value = false;
    getWxBizLogin();
    login_type.value = 1;
  }
}

const getWxBizLoginToken = (trace_id: String) => {
  AuthAPI.wxBizLoginToken({ trace_id }).then(async (res: any) => {
    if (res.access && res.refresh) {
      setToken("Bearer " + res.access); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
      setRefreshToken(res.refresh);
      clearInterval(timeId);
      timeId = null;
      await userStore.getUserInfo();
      await userStore.getSupplierInfo();
      await userStore.getSystemConfig();
      await userStore.getMerchangtInfo();
      await userStore.getAgentInfo();
      if (userStore.isSupplier) {
        webSocketManager.setupWebSocket();
        userStore.fetchBindInviteCode(route.query.invitation_code as string);
      }
      const { path, queryParams } = parseRedirect();
      router.push({ path: path, query: queryParams });
    }
  });
};

function onRefreshQrcode() {
  isExpire.value = false;
  getWxBizLogin();
}

function getWxBizLogin() {
  AuthAPI.wxBizLoginPrepare().then((res: any) => {
    qrcodeUrl.value = res.data.url;
    // let expire_seconds = res.data.expire_seconds;
    let expire_seconds = 120;
    timeId = setInterval(function () {
      expire_seconds = expire_seconds - 2;
      if (expire_seconds <= 0) {
        clearInterval(timeId);
        isExpire.value = true;
        timeId = null;
      } else {
        getWxBizLoginToken(res.data.trace_id);
      }
    }, 2000);
  });
}

/**
 * 解析 redirect 字符串 为 path 和  queryParams
 *
 * @returns { path: string, queryParams: Record<string, string> } 解析后的 path 和 queryParams
 */
function parseRedirect(): {
  path: string;
  queryParams: Record<string, string>;
} {
  const query: LocationQuery = route.query;
  const redirect = (query.redirect as string) ?? "/";

  const url = new URL(redirect, window.location.origin);
  const path = url.pathname;
  const queryParams: Record<string, string> = {};

  url.searchParams.forEach((value, key) => {
    queryParams[key] = value;
  });

  return { path, queryParams };
}

console.log(route.query);

const onLogin = async () => {
  ruleFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      userStore
        .login(login.value)
        .then(async () => {
          await userStore.getUserInfo();
          await userStore.getSupplierInfo();
          await userStore.getMerchangtInfo();
          await userStore.getAgentInfo();
          await userStore.getSystemConfig();
          if (userStore.isSupplier) {
            webSocketManager.setupWebSocket();
          }
          if (route.query.invitation_code) {
            userStore.fetchBindInviteCode(route.query.invitation_code as string);
          }
          if (is_save.value) {
            localStorage.setItem("loginInfo", JSON.stringify(login.value));
          } else {
            localStorage.removeItem("loginInfo");
          }
          loading.value = false;
          const { path, queryParams } = parseRedirect();
          router.push({ path: path, query: queryParams });
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
};

onMounted(() => {
  if (login_type.value === 1) {
    getWxBizLogin();
  } else if (login_type.value === 2) {
    const loginForm = localStorage.getItem("loginInfo");
    if (loginForm) {
      login.value = JSON.parse(loginForm);
      is_save.value = true;
    }
  }
});
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  padding: 20px;
  overflow-y: auto;
  background: url("@/assets/images/loginBg.jpeg") no-repeat center center;
  background-size: cover;

  .login-form {
    width: 390px;
    //height: 520px;
    display: flex;
    flex-direction: column;
    //justify-content: center;
    align-items: center;
    padding: 10px 10px 40px;
    //padding: 40px;
    overflow: hidden;
    background-color: #fff;
    border-radius: 10px;
    box-shadow: var(--el-box-shadow-light);
    position: relative;

    .login-top {
      position: absolute;
      left: 0;
      right: 0;
      top: 15px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 15px;

      .login-top-title {
        font-size: 16px;
        font-weight: bold;
      }

      .login-type {
        color: #3b82f6;
        cursor: pointer;
      }
    }

    @media (width <= 460px) {
      width: 100%;
      padding: 20px;
    }

    .form-title {
      position: relative;
      display: flex;
      align-items: center;
      //justify-content: center;
      padding: 0 0 20px;
      text-align: center;

      & > h2 {
        margin: 30px 0 10px;
      }
    }

    .qrcode-box {
      padding: 5px;
      position: relative;

      .meng-box {
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        top: 0;
        background-color: rgba(0, 0, 0, 0.8);
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;

        .meng-tips {
          color: #ffffff;
          margin-bottom: 10px;
        }
      }
    }

    .login-tips {
      margin-top: 10px;
      color: #666666;
      text-align: center;
    }

    .login-form-content {
      .login-option {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 10px;

        .reset-pass {
          font-size: 14px;
          color: #3b82f6;
        }
      }
    }
  }
}

html.dark {
  .login {
    background: url("@/assets/images/login-bg-dark.jpg") no-repeat center right;
  }
}
</style>
